package com.daoyintech.controllers;

import com.daoyintech.entity.weixin.request.WeixinHongBaoRequest;
import com.daoyintech.entity.weixin.request.WeixinHongBaoEventRequest;
import com.daoyintech.services.WeixinPayService;
import com.daoyintech.utils.MapUtil;
import com.daoyintech.utils.SignatureUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuzhaolin on 15/12/28.
 */
@RestController
@RequestMapping(value="/weixin/hongbao")
public class WeixinHongBaoController implements EnvironmentAware{

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WeixinPayService weixinPayService;

    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,"weixin.");
    }

    private static final String createPacketUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/hbpreorder";
    private static final String createPacketActiveUrl="https://api.weixin.qq.com/shakearound/lottery/addlotteryinfo?";
    private static final String togglePacketUrl = "https://api.weixin.qq.com/shakearound/lottery/setlotteryswitch?access_token={access_token}&lottery_id={lottery_id}&onoff={on_off}";
    private static final String setPrizeBucketUrl="https://api.weixin.qq.com/shakearound/lottery/setprizebucket?";
    private static final String yyyyMMdd = "yyyyMMdd";
    private static final String success_flag = "SUCCESS";
    private static final String fail_flag = "FAIL";

    private String lottery_id;

    @RequestMapping(value="/test")
    public Object test(@RequestBody String code) {
        System.out.println(code);
        return code;
    }


    @RequestMapping(value = "/createPacket")
    public String createPacket() throws Exception {
        String test = initializeHongbao();
        return test;
    }


    @RequestMapping(value = "/createActive")
    public String createActive() throws WxErrorException {
        String access_token = wxMpService.getAccessToken();
        String use_template= "1";
        String logo_url = "http://7sbxgg.com1.z0.glb.clouddn.com/11212.png";
        String url = createPacketActiveUrl+"access_token="+access_token+"&use_template=1"+"&logo_url="+logo_url;
        WeixinHongBaoEventRequest active = new WeixinHongBaoEventRequest();
        active.setTitle("中信银行");
        active.setDesc("红包抽奖");
        active.setOnoff(1);
        active.setBegin_time(getCurrentSeconds());
        active.setExpire_time(getDateSeconds());
        active.setSponsor_appid(propertyResolver.getProperty("appid"));
        active.setTotal(4);
        active.setJump_url("http://www.baidu.com");
        active.setKey(propertyResolver.getProperty("pay_key"));
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(url,active,String.class);
        return result;
    }


    @RequestMapping(value="/bucket")
    public String setBucket(HttpServletRequest request) {
        String lottery_id = request.getParameter("lottery_id");
//        String ticket_num
        return null;

    }


    @RequestMapping(value = "/toggle",method = RequestMethod.GET)
    public String toggle(HttpServletRequest request) throws WxErrorException {
          String lottery_id = request.getParameter("lottery_id");
          String onOff = request.getParameter("onOff");
          String access_token = wxMpService.getAccessToken();
          Map<String,String> params = new HashMap<String, String>();
          params.put("lottery_id",lottery_id);
          params.put("on_off",onOff);
          params.put("access_token",access_token);
          RestTemplate restTemplate = new RestTemplate();
          String result = restTemplate.getForObject(togglePacketUrl,String.class,params);
          return result;
    }



    private String initializeHongbao() throws Exception {
        WeixinHongBaoRequest hongBao = new WeixinHongBaoRequest();
        hongBao.setMch_id(propertyResolver.getProperty("store_id"));
        hongBao.setWxappid(propertyResolver.getProperty("appid"));
        String orderNumber = hongBao.getMch_id()+HongbaoToday()+"1234567891";
        hongBao.setMch_billno(orderNumber);
        hongBao.setSend_name("test user");
        hongBao.setNonce_str("token");
        hongBao.setHb_type("NORMAL");
        hongBao.setTotal_num("1");
        hongBao.setTotal_amount("500");
        hongBao.setAmt_type("ALL_RAND");
        hongBao.setWishing("test");
        hongBao.setAuth_mchid("1000052601");
        hongBao.setAuth_appid("wxbf42bd79c4391863");
        hongBao.setRisk_cntl("NORMAL");
        hongBao.setAct_name("test");
        hongBao.setRemark("remark");
        Map<String,String> params =  MapUtil.objectToMap(hongBao,"sign");
        String key = SignatureUtil.generateSign(params,propertyResolver.getProperty("pay_key"));
        hongBao.setSign(key);
        RestTemplate restTemplate = new RestTemplate(weixinPayService.wxPayHttpClient());
//        RestTemplate restTemplate = new RestTemplate();
        String requestBody = hongBao.toXml();
        String result = restTemplate.postForObject(createPacketUrl,requestBody,String.class);
        return result;
    }






    public static String HongbaoToday(){
        SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMdd);
        return sdf.format(new Date());
    }

    public static long getCurrentSeconds() {
        long currentMilSeconds = System.currentTimeMillis();
        return currentMilSeconds/1000;
    }

    public static long getDateSeconds()  {
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        String dateString = "2016/2/10";
        Date date = null;
        try {
            date = df.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime()/1000;

    }


}
